﻿// Copencv.cpp: 实现文件
//

#include "stdafx.h"
#include "Copencv.h"
#include "IMC_Generic.h"
#include "IMC_GenericDlg.h"



using namespace std;
using namespace cv;


IplImage *image = NULL, *pz_image = NULL;
Mat img1(Size(1240, 1440), CV_8UC3);
Mat g_srcImage, g_dstImage;
vector<vector<Point>> contours;
vector<vector<Point> > contours_poly(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());

VideoCapture  capture1;
BOOL g_bz;
vector<Vec3f> circles;
vector<Vec4i> hierarchy;
 
// Copencv 对话框

 IMPLEMENT_DYNAMIC(Copencv, CDialogEx)

	 Copencv::Copencv(CWnd* pParent /*=nullptr*/)
	 : CDialogEx(IDD_DIG_cv, pParent)
	 , m_element(1)
	 , m_blxs(0)
	 ,m_countline(0)
{
	m_bs = g_cvcfg.bs;
	m_cirdp = g_cvcfg.cirdp;
	m_cirmd = g_cvcfg.cirmd;
	m_yd = g_cvcfg.yd;
	m_fblx = g_cvcfg.fblx;
	m_fbly = g_cvcfg.fbly;
	m_fz1 = g_cvcfg.fz1;
	m_fz2 = g_cvcfg.fz2;
	m_maxcir = g_cvcfg.maxcir;
	m_mincir = g_cvcfg.mincir;
	m_qd1 = g_cvcfg.qy.y;
	m_qd2 = g_cvcfg.qy.x;
	m_qyx = g_cvcfg.fwx;
	m_qyy = g_cvcfg.fwy;

	m_lenline = g_cvcfg.minlen_line;
	m1x = g_cvcfg.m1x;
	m1y = g_cvcfg.m1y;
	m2x = g_cvcfg.m2x;
	m2y = g_cvcfg.m2y;
	im1x = g_cvcfg.im1x;
	im1y = g_cvcfg.im1y;
	im2x = g_cvcfg.im2x;
	im2y = g_cvcfg.im2y;
	m_blxs = g_cvcfg.blxs;
	m_aqjl = g_cvcfg.anql;
	m_gzm = g_cvcfg.gzm;
	
	
}

Copencv::~Copencv()
{
	
}

void Copencv::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, 1003, m_qd1);
	DDX_Text(pDX, 1004, m_qd2);
	DDX_Text(pDX, IDC_EDIT10, m_bs);
	DDX_Text(pDX, 1005, m_qyx);
	DDX_Text(pDX, IDC_EDIT_cvqyy, m_qyy);
	DDX_Text(pDX, IDC_EDIT5, m_lenline);
	DDX_Text(pDX, IDC_EDIT6, m_mincir);
	DDX_Text(pDX, IDC_EDIT7, m_maxcir);
	DDX_Text(pDX, IDC_EDIT8, m_countline);
	DDX_Text(pDX, IDC_EDIT9, m_countcir);
	DDX_Text(pDX, IDC_EDIT11, m_yd);
	DDX_Text(pDX, IDC_EDIT4, m_fblx);
	DDX_Text(pDX, IDC_EDIT12, m_fbly);

	DDX_Text(pDX, IDC_EDIT1, m_element);
	DDV_MinMaxInt(pDX, m_element, 0, 200);
	DDX_Text(pDX, IDC_EDIT3_fz2, m_fz2);
	DDX_Text(pDX, IDC_EDIT2_fz1, m_fz1);
	DDX_Text(pDX, IDC_EDIT_dp, m_cirdp);
	DDV_MinMaxInt(pDX, m_cirdp, 1, INT_MAX);
	DDX_Text(pDX, IDC_EDIT_md, m_cirmd);

	DDX_Text(pDX, 1017, m1x);
	DDX_Text(pDX, 1018, m1y);
	DDX_Text(pDX, 1020, m2x);
	DDX_Text(pDX, 1021, m2y);
	DDX_Text(pDX, IDC_EDIT_IM1X, im1x);
	DDX_Text(pDX, IDC_EDIT_IM1Y, im1y);
	DDX_Text(pDX, IDC_EDIT_IM2X, im2x);
	DDX_Text(pDX, IDC_EDIT_IM2Y, im2y);

	DDX_Control(pDX, IDC_COMBO_gjlx, m_gjlx);
	
	DDX_Text(pDX, IDC_EDIT_aqjl, m_aqjl);
	DDX_Text(pDX, IDC_EDIT_gzm, m_gzm);
}


BEGIN_MESSAGE_MAP(Copencv, CDialogEx)
	ON_BN_CLICKED(IDCANCEL, &Copencv::OnBnClickedCancel)
	ON_WM_TIMER()
	ON_BN_CLICKED(1000, &Copencv::OnBnClicked1000)
//	ON_BN_CLICKED(IDOK, &Copencv::OnBnClickedOk)
	//ON_BN_CLICKED(1001, &Copencv::OnBnClicked1001)
	ON_BN_CLICKED(IDC_BUTTON1_openca, &Copencv::OnBnClickedButton1openca)
//	ON_BN_CLICKED(IDC_BUTTON_auotprg, &Copencv::OnBnClickedButtonauotprg)
ON_BN_CLICKED(IDC_BUTTON_savecfg, &Copencv::OnBnClickedButtonsavecfg)
ON_BN_CLICKED(IDC_BUTTON_setbd1, &Copencv::OnBnClickedButtonsetbd1)
ON_BN_CLICKED(IDC_BUTTON1_MABD, &Copencv::OnBnClickedButton1Mabd)
ON_BN_CLICKED(IDC_BUTTON_setbd2, &Copencv::OnBnClickedButtonsetbd2)
ON_BN_CLICKED(IDC_BUTTON_cat, &Copencv::OnBnClickedButtoncat)
ON_BN_CLICKED(IDC_BUTTON1, &Copencv::OnBnClickedButton1)
END_MESSAGE_MAP()


// Copencv 消息处理程序


void Copencv::OnBnClickedCancel()
{
	CIMC_GenericDlg *pDlg = (CIMC_GenericDlg *)m_mdlg;
	// TODO: 在此添加控件通知处理程序代码
	int qr = MessageBox(_T("不保存参数退出吗？"), _T("确认"), MB_OKCANCEL);
	if (qr == 1)
	{
			capture1.release();
			Invalidate();
	
		GetDlgItem(1000)->SetWindowText(_T("开始捕捉"));
		m_countcir = 0;
		m_countline = 0;
		g_bz = false;
		//pDlg->m_maindlg.OnBnClickedButtonopencam();
		CDialogEx::OnOK();
	}
	else
		OnBnClickedButtonsavecfg();

}




void Copencv::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	if (nIDEvent == TIMER_CVDEBUG)
	{
		Mat sc;
		capture1 >> sc;
		//sc=imread("d://1.jpg");
	//	flip(sc, img1, -1);
		//imshow("a", img1);
		//waitKey(0);
		img1 = sc.clone();
		Mat scr1 = img1.clone();
		Rect rc;
		
		rc.y = GetDlgItemInt(1003);// g_cvcfg.qy.y;
		rc.x = GetDlgItemInt(1004);//g_cvcfg.qy.x;
		rc.width = GetDlgItemInt(IDC_EDIT_cvqyy);
		rc.height = GetDlgItemInt(1005);// g_cvcfg.fw;
		rectangle(scr1, rc, Scalar(0, 50, 255), 4, 0);
		
		Mat imagedst;
		//以下操作获取图形控件尺寸并以此改变图片尺寸  
		CRect rect;
		GetDlgItem(IDC_STATIC_ts)->GetClientRect(&rect);
		Rect dst(rect.left, rect.top, rect.right, rect.bottom);
		resize(scr1, imagedst, Size(rect.Width(), rect.Height()));
		//imshow("view", imagedst);      
		image = &IplImage(imagedst);
		
		DrawPicToHDC(image, IDC_STATIC_ts);
	}
	
	CDialogEx::OnTimer(nIDEvent);
}
void  Copencv::DrawPicToHDC(IplImage *img, UINT ID)
{

	CDC *pDC = GetDlgItem(ID)->GetDC();
	HDC hDC = pDC->GetSafeHdc();

	CRect rect;
	GetDlgItem(ID)->GetClientRect(&rect);
	CvvImage cimg;
	cimg.CopyOf(img, 1); // 复制图片
	cimg.DrawToHDC(hDC, &rect); // 将图片绘制到显示控件的指定区域内
	ReleaseDC(pDC);


}


BOOL Copencv::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// TODO:  在此添加额外的初始化
	g_bz = false;
	GetDlgItem(1000)->SetWindowText(_T("开始捕捉"));
	GetDlgItem(1000)->ShowWindow(SW_HIDE);

	SetDlgItemInt(IDC_EDIT_MANDX, 0);
	SetDlgItemInt(IDC_EDIT_MANDY, 0);
	SetDlgItemInt(IDC_EDIT_MANDD, 220);
	CComboBox* pb = (CComboBox*)GetDlgItem(IDC_COMBO_gjlx);
	pb->AddString(_T("X升序Y升序"));
	pb->AddString(_T("X升序Y降序"));
	pb->AddString(_T("X降序Y升序"));
	pb->AddString( _T("X降序Y降序"));
	pb->AddString(_T(" Y升序X升序"));
	pb->AddString(_T("Y升序X降序"));
	pb->AddString(_T("Y降序X升序"));
	pb->AddString(_T("Y降序X降序"));

	m_gjlx.SetCurSel(g_cvcfg.gjlx);
	
	//m_blxs = g_cvcfg.blxs;
	//CString cb;
	//cb.Format(_T("%6f"), m_blxs);
	//SetDlgItemText(IDC_EDIT_blxs, cb);

	//GetDlgItem(1001)->ShowWindow(SW_HIDE);

	/*capture.open(0);
	if (capture.isOpened())
	{
		capture.set(CV_CAP_PROP_FRAME_WIDTH, m_fblx);
		capture.set(CV_CAP_PROP_FRAME_HEIGHT, m_fbly);
		SetTimer(1, 30, NULL);
		GetDlgItem(1000)->ShowWindow(SW_SHOW);
	}*/
	return TRUE;  // return TRUE unless you set the focus to a control
				  // 异常: OCX 属性页应返回 FALSE
}


void Copencv::OnBnClicked1000()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(true);
	if (g_bz == true)
	{
		Invalidate();
		SetTimer(TIMER_CVDEBUG, 30, NULL);
		g_bz = false;
		m_countcir = 0;
		m_countline = 0;
		UpdateData(false);
		//GetDlgItem(1001)->ShowWindow(SW_HIDE);
		GetDlgItem(1000)->ShowWindow(SW_SHOW);
		GetDlgItem(1000)->SetWindowText(_T("开始捕捉"));
		
		
	}
	else
	{
		if ( ((m_qyy + m_qd2) > m_fblx) || ((m_qyx + m_qd1) > m_fbly))
		{
		  MessageBox(_T("识别区域设置超出范围"));
        }
		else
		{
			KillTimer(TIMER_CVDEBUG);
			m_countline = 0;
			m_countcir = 0;
			//capture >> g_srcImage;
			Mat result1;
			result1 = img1.clone();
			//imwrite("d:/qq.jpg", result1);
			//if (!(m_bs == 1))
			//{
				Rect rect1(m_qd2, m_qd1, m_qyy, m_qyx);
				//Rect rect1(260, 680, 200,40);
				 result1 = img1(rect1);
			//}
		//	double bs = round(m_bs*m_qy);
			// m_bs
			Mat r1;
			if (!(m_bs == 1))
			{
				resize(result1, r1, Size(result1.cols*m_bs, result1.rows*m_bs), (0, 0), (0, 0), 3);
			}
			else
			{
				r1 = result1.clone();
			}

			g_srcImage = r1.clone();
			
			g_cvcfg.gjlx = m_gjlx.GetCurSel();
			vector<Point2f> centery1;
			vector<float> radiusy1;
			houcir(centery1, radiusy1);
			if (centery1.size() > 1)
			{
				m_img1x = centery1[1].y;
				m_img1y = centery1[1].x;
				m_img2x = centery1[0].y;
				m_img2y = centery1[0].x;
			}
			//Contorscir(centery1, radiusy1);
			for (int unsigned i = 0; i < centery1.size(); i++)
			{

				Scalar color = Scalar(155, 50, 255);
				circle(result1, centery1[i] / m_bs, (int)radiusy1[i] / m_bs, color, 2, 8, 0);//绘制圆
				circle(result1, centery1[i] / m_bs, 3, Scalar(0, 255, 0), -1, 8, 0);//绘制圆心
				Point p1, p2, p3, p4;
				p1.x = (centery1[i].x - radiusy1[i])/m_bs;
				p1.y = centery1[i].y / m_bs;
				p2.x = (centery1[i].x + (int)radiusy1[i]) / m_bs;
				p2.y = centery1[i].y / m_bs;
				line(result1, p1, p2, Scalar(0,0, 255),  2, CV_AA);
				p3.y = centery1[i].y - (int)radiusy1[i];
				p3.x = centery1[i].x;
				p4.y = centery1[i].y + (int)radiusy1[i];
				p4.x = centery1[i].x;
				line(result1, p3, p4, Scalar(0, 0,255),  2, CV_AA);
				char lsstr[3];
				itoa(i+1, lsstr, 10);
				Point pp;
				pp.x = centery1[i].x+15;
				pp.y = centery1[i].y+15 ;
				putText(result1, lsstr, pp, CV_FONT_HERSHEY_SIMPLEX, 1.8f, CV_RGB(255, 0, 0), 2, 8);
			}
			//line(result1, Point(10, 10), Point(500, 100), Scalar(0, 0, 255), 5, CV_AA);
			//imshow("p", g_srcImage);
			//imshow("p1", result1);
			g_bz = true;
			pz_image = &IplImage(img1);
			DrawPicToHDC(pz_image, IDC_STATIC_ts);

			UpdateData(true);
			//GetDlgItem(1001)->ShowWindow(SW_HIDE);

			GetDlgItem(1000)->SetWindowText(_T("重新捕捉"));
		//	GetDlgItem(1001)->ShowWindow(SW_SHOW);
		}
	}
}



BOOL Copencv::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (WM_KEYDOWN == pMsg->message && VK_RETURN == pMsg->wParam)

	{
		//if (GetFocus() == GetDlgItem(IDC_EDIT1))//根据不同控件焦点判断是那个在执行 
		if (pMsg->wParam == VK_ESCAPE || pMsg->wParam == VK_RETURN)
		//{
			//UpdateData(TRUE);
			return TRUE;
		//}


		
	}
	return CDialogEx::PreTranslateMessage(pMsg);
}
//轮廓圆识别
void Copencv::Contorscir(vector<Point2f>&centery,vector<float>&radiusy)
{
	   	  
	int g_nElementShape = MORPH_RECT;//元素结构的形状
	Mat edge, grayImage, g_midImage;

	int iLowH = 0;
	int iHighH = 180;

	int iLowS = 0;
	int iHighS = 30;

	int iLowV = 221;
	int iHighV = 255;
	//自定义核
	//UpdateData(true);
	Mat element = getStructuringElement(g_nElementShape, Size(m_element * 2 + 1, m_element * 2 + 1), Point(m_element, m_element));

	Mat imgHSV;
	Mat colorHeqImage;
	vector<Mat> hsvSplit;
	cvtColor(g_srcImage, colorHeqImage, COLOR_BGR2HSV);
	//转化成直方图均衡化
	split(colorHeqImage, hsvSplit);
	equalizeHist(hsvSplit[2], hsvSplit[2]);
	merge(hsvSplit, imgHSV);
	


	//彩色直方图均衡化后显示
	
	
	Mat imgThresholded;
	
	//确定颜色显示的范围
	inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded);
	
	//颜色过滤
	//threshold(g_srcImage, imgThresholded, 3, 255, THRESH_BINARY);
	threshold(imgThresholded, imgThresholded, 50, 255, THRESH_BINARY);
	morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element); // 闭操作(连接一些连通域)
	morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);// 开操作(去除一些噪点)
	
	morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);
	
	blur(imgThresholded, imgThresholded, Size(3, 3));
	//Canny(imgThresholded, edge, m_fz1,m_fz2, 3);
	//imshow("o", imgThresholded);

	findContours(imgThresholded, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	if (contours.size() > 0)
	{

		contours_poly.resize(contours.size());
		center.resize(contours.size());
		radius.resize(contours.size());
		for (unsigned int i = 0; i < contours.size(); i++)
		{
			approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);//用指定精度逼近多边形曲线 
			minEnclosingCircle(contours_poly[i], center[i], radius[i]);//对给定的 2D点集，寻找最小面积的包围圆形 
		}

		int jj = hbtxy(center, radius);

		centery.resize(jj);
		radiusy.resize(jj);
		m_countcir = radiusy.size();
		UpdateData(false);
		int j = 0;
		for (int unsigned i = 0; i < m_countcir; i++)
		{

			Scalar color = Scalar(155, 50, 255);
			if ((radius[i] > m_mincir) && (radius[i] < m_maxcir))
			{
				circle(g_srcImage, center[i], (int)radius[i], color, 2, 8, 0);//绘制圆
				circle(g_srcImage, center[i], 3, Scalar(0, 255, 0), -1, 8, 0);//绘制圆心
				/*Point p1, p2,p3,p4;
				p1.x = center.at(i).x - (int)radius[i];
				p1.y = center.at(i).y ;
				p2.x = center.at(i).x + (int)radius[i];
				p2.y = center.at(i).y;
				line(g_srcImage, p1, p2, Scalar(0, 255, 0), -1, 8, 0);
				p3.y = center.at(i).y - (int)radius[i];
				p3.x = center.at(i).x;
				p4.y = center.at(i).y + (int)radius[i];
				p4.x = center.at(i).x;
				line(g_srcImage, p3, p4, Scalar(0, 255, 0), -1, 8, 0);*/
				radiusy.at(j) = radius.at(i);
				centery.at(j) = center.at(i);
				j++;
				
			}
		}
		g_dstImage = g_srcImage.clone();// 
	
	}
}

void Copencv::OnBnClickedButton1openca()
{
	// TODO: 在此添加控件通知处理程序代码

	
	if (!capture1.isOpened())
	{
		UpdateData(TRUE);
		capture1.open(0);
		if (capture1.isOpened())
		{
			capture1.set(CV_CAP_PROP_FRAME_WIDTH, m_fblx);
		    capture1.set(CV_CAP_PROP_FRAME_HEIGHT, m_fbly);
		}
		else
		{
			MessageBox(_T("相机打开失败"));
			return;
		}
	}
	UpdateData(true);
	GetDlgItem(IDC_BUTTON1_openca)->ShowWindow(SW_HIDE);
	g_bz = false;
	GetDlgItem(1000)->SetWindowText(_T("开始捕捉"));
	GetDlgItem(1000)->ShowWindow(SW_SHOW);
	//GetDlgItem(1001)->ShowWindow(SW_HIDE);
	SetTimer(TIMER_CVDEBUG, 30, NULL);
}
//霍夫圆
void Copencv::houcir(vector<Point2f>&centery, vector<float>&radiusy)
{
	//destroyAllWindows();
	int g_nElementShape = MORPH_RECT;//元素结构的形状
	Mat edge, grayImage, g_midImage;

	int iLowH = 0;
	int iHighH = 180;

	int iLowS = 0;
	int iHighS = 30;

	int iLowV = 221;
	int iHighV = 255;
	//自定义核
	//UpdateData(true);


	Mat element = getStructuringElement(g_nElementShape, Size(m_element * 2 + 1, m_element * 2 + 1), Point(m_element, m_element));

	Mat imgHSV;
	Mat midImage;
	vector<Mat> hsvSplit;


	cvtColor(g_srcImage, midImage, COLOR_BGR2GRAY);
	GaussianBlur(midImage, midImage, Size(9, 9), 2, 2);
	morphologyEx(midImage, midImage, MORPH_CLOSE, element); // 闭操作(连接一些连通域)
	morphologyEx(midImage, midImage, MORPH_OPEN, element);// 开操作(去除一些噪点)

	morphologyEx(midImage, midImage, MORPH_OPEN, element);
	//imshow("po", midImage);
	HoughCircles(midImage, circles, HOUGH_GRADIENT, m_cirdp, m_cirmd, m_fz1, m_yd, m_mincir, m_maxcir);
	m_countcir = circles.size();
	vector<Point2f>center1(40);
	vector<float>radius1(40);
	if (m_countcir > 0)
	{
		//【5】依次在图中绘制出圆
		for (size_t i = 0; i < circles.size(); i++)
		{
			//参数定义
			center1.at(i).x = circles.at(i)(0);
			center1.at(i).y = circles.at(i)(1);
			radius1.at(i)= circles.at(i)(2);
			
		}

	}

	int jj = hbtxy(center1, radius1);
	centery.resize(jj);
	radiusy.resize(jj);
	m_countcir = radiusy.size();
	UpdateData(false);
	int j = 0;
	for (int unsigned i = 0; i < m_countcir; i++)
	{

		Scalar color = Scalar(155, 50, 255);
		radiusy.at(j) = radius1.at(i);
		centery.at(j) = center1.at(i);
		j++;

	}
	g_dstImage = g_srcImage.clone();
	
	
}


//外部调用
void  Copencv::outcir(Mat &im, vector<Point2f>&centery,vector<float>&radiusy)
{

	img1 = im.clone();
	loadcfgcv();
	//double bs = round(m_bs*m_qy);
	//g_srcImage = _dst.getMat();
	Rect rect1(m_qd2, m_qd1, m_qyy, m_qyx);
	Mat result1 = img1(rect1);
	Mat r1;
	
	//resize(result1, r1, Size(bs, bs), (0, 0), (0, 0), 3);
	//imshow("p", r1);
	//Mat r1;
	if (!(m_bs == 1))
	{
		resize(result1, r1, Size(result1.cols*m_bs, result1.rows*m_bs), (0, 0), (0, 0), 3);
	}
	else
	{
		r1 = result1.clone();
	}

	g_srcImage = r1.clone();
	//Contorscir(centery, radiusy);

	houcir(centery, radiusy);
	for (int unsigned i = 0; i < centery.size(); i++)
	{

		Scalar color = Scalar(155, 50, 255);
			circle(result1, centery[i]/m_bs, (int)radiusy[i]/m_bs, color, 5, 8, 0);//绘制圆
			circle(result1, centery[i] / m_bs, 3, Scalar(0, 255, 0), -1, 8, 0);//绘制圆心
			
			
	}
	
	
	
	im = img1.clone();// g_dstImage.clone();
}
void Copencv::savecfgcv()
{
	
	UpdateData(TRUE);
	
	g_cvcfg.bs = m_bs;
	g_cvcfg.cirdp = m_cirdp;
	g_cvcfg.cirmd = m_cirmd;
	g_cvcfg.yd = m_yd;
	g_cvcfg.fblx = m_fblx;
	g_cvcfg.fbly = m_fbly;
	g_cvcfg.fz1 = m_fz1;
	g_cvcfg.fz2 = m_fz2;
	g_cvcfg.maxcir = m_maxcir;
	g_cvcfg.mincir = m_mincir;
	g_cvcfg.qy.y = m_qd1;
	g_cvcfg.qy.x = m_qd2;
	g_cvcfg.fwx = m_qyx;
	g_cvcfg.fwy = m_qyy;
	g_cvcfg.minlen_line = m_lenline;
	g_cvcfg.m1x = m1x;
	g_cvcfg.m1y = m1y;
	g_cvcfg.m2x = m2x;
	g_cvcfg.m2y = m2y;
	g_cvcfg.im1x = im1x;
	g_cvcfg.im1y = im1y;
	g_cvcfg.im2x = im2x;
	g_cvcfg.im2y = im2y;
	g_cvcfg.blxs = m_blxs;
	g_cvcfg.gjlx = m_gjlx.GetCurSel();
	g_cvcfg.anql = GetEditFloat (IDC_EDIT_aqjl);
	g_cvcfg.gzm = GetEditFloat(IDC_EDIT_gzm);
	
}
void Copencv::loadcfgcv()
{
	m_bs = g_cvcfg.bs;
	m_cirdp =g_cvcfg.cirdp;
	m_cirmd = g_cvcfg.cirmd;
	m_yd = g_cvcfg.cphd;
	m_fblx = g_cvcfg.fblx;
	m_fbly = g_cvcfg.fbly;
	m_fz1 = g_cvcfg.fz1;
	m_fz2 = g_cvcfg.fz2;
	m_maxcir = g_cvcfg.maxcir;
	m_mincir = g_cvcfg.mincir;
	m_qd1 = g_cvcfg.qy.y;
	m_qd2 = g_cvcfg.qy.x;
	m_qyx = g_cvcfg.fwx;
	m_qyy = g_cvcfg.fwy;
	m_lenline = g_cvcfg.minlen_line;
	m1x = g_cvcfg.m1x;
	m1y = g_cvcfg.m1y;
	m2x = g_cvcfg.m2x;
	m2y = g_cvcfg.m2y;
	im1x = g_cvcfg.im1x;
	im1y = g_cvcfg.im1y;
	im2x = g_cvcfg.im2x;
	im2y = g_cvcfg.im2y;
	m_gjlx.SetCurSel(g_cvcfg.gjlx);
	m_aqjl = g_cvcfg.anql;
	m_gzm = g_cvcfg.gzm;
	m_yd = g_cvcfg.yd;
}
void Copencv::OnBnClickedButtonsavecfg()
{
	// TODO: 在此添加控件通知处理程序代码
	savecfgcv();
	SavecvCfg();
	KillTimer(TIMER_CVDEBUG);
	capture1.release();
	Invalidate();
	//CIMC_GenericDlg *pDlg = (CIMC_GenericDlg *)m_mdlg;
	//pDlg->m_maindlg.OnBnClickedButtonopencam();

	CDialogEx::OnOK();
}
//合并同心圆
bool Copencv::sortFun1(const pstr &ps1, const pstr& ps2)//  X升
{
	return ps1.b < ps2.b;
}
bool Copencv::sortFun2(const pstr &ps1, const pstr& ps2)//  X降
{
	return ps1.b > ps2.b;
}
bool Copencv::sortFun3(const pstr &ps1, const pstr& ps2)//  Y升
{
	return ps1.a < ps2.a;
}
bool Copencv::sortFun4(const pstr &ps1, const pstr& ps2)//  Y降
{
	return ps1.a > ps2.a;
}

int Copencv::hbtxy(vector<Point2f>&center, vector<float>&radius)
{
	
	int countcir = 0, size_center=center.size();
	vector<Point2f>cen(size_center);
	vector<float>rad(size_center);
	vector<pstr> po;
	pstr p;
	int count = center.size();
	for (int xh = 0; xh < count; xh++)
	{
	
		p.a = center.at(xh).x;
		p.b = center.at(xh).y;
		p.r = radius.at(xh);
		po.push_back(p);
	}
	int rmin = m_mincir;
	int rmax = m_maxcir;

	
	po.erase(remove_if(po.begin(), po.end(), [rmin, rmax](pstr n) {return n.r < rmin || n.r > rmax; }), po.end());//圆直径过滤
	//根据行列优先级排序
	switch (g_cvcfg.gjlx)
	{
	case XSYS: case XSYJ:
	{
		sort(po.begin(), po.end(), sortFun1);	break; };
	
	case XJYS:	case XJYJ:
	{ sort(po.begin(), po.end(), sortFun2); break; };

	
	case YSXS: case YSXJ:
	{ sort(po.begin(), po.end(), sortFun3); break;  };
	
	case YJXS:case YJXJ:
	{  sort(po.begin(), po.end(), sortFun4); break; };
	
	default:
		break;
	}
	//内排序
	int counts = po.size();
	vector <pstr>::iterator it;// = po.begin();
	vector <pstr>::iterator ite;// = it;
	int be, en;
	bool npxhx = true;//内排序换行标记

	if (counts > 1)
	{
		be = 0;
		it = po.begin()+be;
		en = 1;
		ite = po.begin()+en;
		while (en < counts)
		{
			bool tj = abs(po.at(en).b - po.at(be).b)>(g_cvcfg.cpwj/g_cvcfg.blxs);
			if (tj)
			{
				if ((en - be) > 1)
				{
					switch (g_cvcfg.gjlx)
					{
					case XSYS: case XJYS:
					{
						if (npxhx)	sort(it, ite, sortFun3);
						else		sort(it, ite, sortFun4);
						npxhx = !npxhx;//换向
						break; 	};
					case XSYJ: case XJYJ:
					{ 
						if (npxhx) sort(it, ite, sortFun4);
						else	   sort(it, ite, sortFun3);
						npxhx = !npxhx;//换向
						break; };
					
					case YSXS:	case YJXS:
					{ 
						if (npxhx) sort(it, ite, sortFun1);
						else       sort(it, ite, sortFun2);
						npxhx = !npxhx;//换向
						break; };
					case YSXJ:	case YJXJ:
					{
						if (npxhx)	sort(it, ite, sortFun2);
						else		sort(it, ite, sortFun1);
						npxhx = !npxhx;//换向
						break; };
				
					default:
						break;
					}
			}
				be = en;
				en = be + 1;
				it = po.begin() + be;
		}
			else
			{
				en++;
			}
			ite = po.begin() + en;
		}
	}



	//圆心距过滤；
	countcir = 0;
	int unsigned i = 0;
	//取第一个直径符合要求的圆
	while (i < po.size()/*size_center*/)
	{
	
			cen.at(countcir).x = po.at(i).a;
			cen.at(countcir).y = po.at(i).b;
			rad.at(countcir) = po.at(i).r;
			countcir++;
	
		i++;
	};

	int js = (size_center - 1);
	if (i < size_center)//容器里还有元素则遍历比较
	{
		for (int unsigned j = i + 1; j <= js;j++)
		{
			if ((radius[j] > m_mincir) && (radius[j] < m_maxcir))
			{
				bool txybz{ false };
				int unsigned ii = 0; 
				while (ii <= (countcir - 1) )
				{
					float dist1 = abs(pow((cen.at(ii).x - center.at(j).x), 2));
					float dist2 = abs(pow((cen.at(ii).y - center.at(j).y), 2));
					float dist = sqrt(dist1 + dist2);
					if (dist < m_cirmd )
					{
						txybz = TRUE;
						if (radius.at(ii) > rad.at(j)) rad.at(j) = radius.at(ii);
						//break;
					}
					ii++;
				}
				if (!txybz)
				{
					cen.at(countcir) = center.at(j);
					rad.at(countcir) = radius.at(j);
					countcir++;
				}
			}

		}
	}
	//结果显示
	if (!(countcir == 0))
	{
		center.resize(countcir);
		radius.resize(countcir);
		CString str1;
		char count[100];
		Point gd;
		double rd;
		for (int unsigned j = 0; j < (countcir); j++)
		{
			center.at(j).x = cen.at(j).x;
			center.at(j).y = cen.at(j).y;
			radius.at(j) = rad.at(j);// 
			
			//显示识别结果
			gcvt(center.at(j).x, 5, count);
			str1 += count;
			str1 += _T("   ");
			gcvt(center.at(j).y, 5, count);
			str1 += count;
			str1 += _T("   ");
			gcvt(radius.at(j), 5, count);
			str1 += count;
			str1 += _T("\r\n");
		}
	SetDlgItemText(IDC_EDIT_sbjgcv, str1);
		
		return countcir;
		
	}
	else
		return 0;

}
double  Copencv::GetEditFloat(UINT id)
{
	WCHAR data[16];
	double dval;
	int len = GetDlgItemText(id, data, 15);
	if (len == 0) return 0;
	data[len] = 0;
	swscanf(data, _T("%lf"), &dval);
	return dval;
}

void Copencv::OnBnClickedButtonsetbd1()
{
	// TODO: 在此添加控件通知处理程序代码
	im1x = GetDlgItemInt(IDC_EDIT_MANDY);
	im1y = GetDlgItemInt(IDC_EDIT_MANDX);
	UpdateData(false);
}


void Copencv::OnBnClickedButton1Mabd()
{
	// TODO: 在此添加控件通知处理程序代码

	if (!capture1.isOpened())
	{
	
			return;
		
	}
	//SetTimer(TIMER_MABD, 30, NULL);
	//Sleep(500);
	KillTimer(TIMER_CVDEBUG);
	Mat result1;
	//Mat img2 = imread("d://1.jpg");
	result1 = img1.clone();

	

	Rect rect1(m_qd2, m_qd1, m_qyy, m_qyx);
	//Rect rect1(10, 10, 200, 200);
	//Rect rect1(260, 680, 200,40);
	result1 = img1(rect1);

	
	Point xs;
	Scalar color = Scalar(155, 50, 255);
	xs.x = GetEditFloat(IDC_EDIT_MANDX);
	xs.y = GetEditFloat(IDC_EDIT_MANDY);
	int xsd = GetEditFloat(IDC_EDIT_MANDD);
	circle(result1, xs, xsd, color, 2, 8, 0);//绘制圆
	circle(result1, xs, 3, Scalar(0, 255, 0), -1, 8, 0);//绘制圆心
	Mat scr1 = img1.clone();
//	imshow("sss", scr1);
	image = &IplImage(scr1);

	DrawPicToHDC(image, IDC_STATIC_ts);
	UpdateData(true);
	//SetTimer(TIMER_MABD, 30, NULL);
}


void Copencv::OnBnClickedButtonsetbd2()
{
	// TODO: 在此添加控件通知处理程序代码
	im2x = GetDlgItemInt(IDC_EDIT_MANDY);
	im2y = GetDlgItemInt(IDC_EDIT_MANDX);
	UpdateData(false);
}


void Copencv::OnBnClickedButtoncat()
{
	// TODO: 在此添加控件通知处理程序代码
	KillTimer(TIMER_CVDEBUG);
	Rect rect1(m_qd2, m_qd1, m_qyy, m_qyx);
	//Rect rect1(260, 680, 200,40);
	Mat result1 = img1(rect1);
	//imshow("_T(df)", img1);
	//imshow("_T(df1)", result1);
	vector<int> compression_params;
	compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); //PNG格式图片的压缩级别  
	compression_params.push_back(9);  //这里设置保存的图像质量级别
	
	imwrite("jty.png", img1, compression_params);
	imwrite("jtre.png", result1, compression_params);
	SetTimer(TIMER_CVDEBUG, 30, NULL);
}


void Copencv::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	SetDlgItemInt(IDC_EDIT_IM1X,m_img1x);
	SetDlgItemInt(IDC_EDIT_IM1Y, m_img1y);
	SetDlgItemInt(IDC_EDIT_IM2X, m_img2x);
	SetDlgItemInt(IDC_EDIT_IM2Y, m_img2y);

	UpdateData(true);
}
